package com.ojoin.ojoin.eb_spider.service.catchdata;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.io.IOUtils;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.ojoin.ojoin.eb_spider.domain.AssistCatchData;
import com.ojoin.ojoin.eb_spider.domain.BankCardCheck;
import com.ojoin.ojoin.eb_spider.service.WebDriverService;
import com.ojoin.ojoin.eb_spider.service.impl.SLDataCatchBaseServiceImpl;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.TimeUtils;
import com.ojoin.trade.common.utils.WaitUtil;
import com.ojoin.trade.common.utils.excel.Excel2003Writer;
import com.ojoin.trade.common.utils.excel.ExcelReaderUtil;
import com.ojoin.trade.common.utils.excel.IRowReader;

/**
 * 
 * 
 * 
 */

@Service
public class MeidiDataCatchServiceImpl extends SLDataCatchBaseServiceImpl {
	private static Logger log = LoggerFactory
			.getLogger(MeidiDataCatchServiceImpl.class);
	private static Map<String, Map<String, List<String>>> map = new HashMap<String, Map<String, List<String>>>();

	private static Set<String> set = new HashSet<String>();

	{
		Map<String, List<String>> mp = new HashMap<String, List<String>>();
		List<String> li = new ArrayList<String>();
		li.add("陶瓷板");
		mp.put("外观类-外观破损", li);
		map.put("电磁炉", mp);

		mp = new HashMap<String, List<String>>();
		li = new ArrayList<String>();
		li.add("内锅");
		li.add("电热盘");
		mp.put("外观类-外观破损", li);
		map.put("电饭锅", mp);
		map.put("电饭煲", mp);
		map.put("方煲", mp);

		mp = new HashMap<String, List<String>>();
		li = new ArrayList<String>();
		li.add("外壳");
		mp.put("外观类-外观破损", li);
		map.put("电水壶", mp);

		mp = new HashMap<String, List<String>>();
		li = new ArrayList<String>();
		li.add("电热盘");
		li.add("上盖");
		mp.put("外观类-外观破损", li);
		
		map.put("电饼铛", mp);
 
		mp = new HashMap<String, List<String>>();
		li = new ArrayList<String>();
		li.add("内锅");
		li.add("发热盘");
		mp.put("外观类-外观破损", li);
		mp.put("外观类-外观损坏", li);
		map.put("电压力锅", mp);
		map.put("", mp);

		mp = new HashMap<String, List<String>>();
		li = new ArrayList<String>();
		li.add("搅拌杯");
		li.add("外壳");
		li.add("底盖");
		
		mp.put("外观类-外观破损", li);
		mp.put("外观类-外观损坏", li);
	
		map.put("榨汁机", mp);
		map.put("原汁机", mp);
		map.put("果汁机", mp);
		
		mp = new HashMap<String, List<String>>();
		li = new ArrayList<String>();
		li.add("外壳");
		li.add("内胆");
		mp.put("外观类-外观破损", li);
		map.put("豆浆机", mp);
		map.put("开水瓶", mp);
		map.put("电热水瓶", mp);

		mp = new HashMap<String, List<String>>();
		li = new ArrayList<String>();
		li.add("底座");
		mp.put("外观类-外观损坏", li);
		map.put("煎烤机", mp);
		
		mp = new HashMap<String, List<String>>();
		li = new ArrayList<String>();
		li.add("底座");
		mp.put("外观类-外观损坏", li);
		map.put("煎烤机", mp);
		
		set = map.keySet();

	}

	@Override
	public boolean isLoginSuccess() throws Exception {
		boolean loginflag = false;

		String username = this.getAssistCatchData().getStartMess()
				.getPlatformUser().getUsername();
		String password = this.getAssistCatchData().getStartMess()
				.getPlatformUser().getPassword();

		String loginUrl = this.getAssistCatchData().getStartMess()
				.getPlatformInfo().getLoginUrl();

		loginflag = LoginByUserInfo(loginUrl, username, password);

		return loginflag;
	}

	@Override
	public boolean LoginByUserInfo(String baseUrl, String username,
			String password) {
		// 开始登陆
		try {
			this.getWebDriver()
					.get("http://202.104.30.176/mcss/login.do;jsessionid=ybrvXG8LY37pT6g2yKYbQnNXgj6kVYLv2S01nnHsZ0P8pHx9WJRQ!-458205313?method=begin");
			this.getWebDriver()
					.get("http://202.104.30.176/mcss/login.do;jsessionid=ybrvXG8LY37pT6g2yKYbQnNXgj6kVYLv2S01nnHsZ0P8pHx9WJRQ!-458205313?method=begin");

			this.getWebDriver().sendKeys("id", "j_username", username);
			this.getWebDriver().sendKeys("id", "j_password", password);

			this.getWebDriver().click("id", "btnImg");

		} catch (Exception e) {
			LogUtils.info(log, e.getMessage());
		}

		return this
				.getWebDriver()
				.isLogin(
						"http://202.104.30.176/mcss/enterapp.do?method=begin&name=/mcss&welcome=/mcss/pages/index.jsp");
	}

	@Override
	public void catchData(AssistCatchData assistCatchData) throws Exception {
		super.init(assistCatchData);

		try {
			prepareCatchData();

			boolean flag = isLoginSuccess();

			if (flag) {

				Set<String> sets = readExce();

				open();
				

				if (!CommonUtils.isEmpty(sets)) {
					int i = 0 ;
					for (String oms : sets) {
						i++;
						if(i> 300){
							return ;
						}
						boolean success = doit(oms);
						if(success){
							LogUtils.info(log, oms+"成功");
							saveExcel(oms,success);
						}else {
							LogUtils.info(log, oms+"失败");
							saveExcel(oms,success);
						}
						

					}
				}

			}

		} catch (Exception e) {
			LogUtils.error(log, e.toString());
			throw e;

		} finally {

		}
	}

	public static void main(String[] args) throws Exception {
		// saveExcel("3698");
		MeidiDataCatchServiceImpl mm = new MeidiDataCatchServiceImpl();

		Set<String> sets = mm.readExce();
	}

	public static void saveExcel(String oms,boolean flag) throws Exception {
		try {
			List<List<String>> list = new ArrayList<List<String>>();

			List<String> li = new ArrayList<String>();

			li.add("");
			li.add("");
			li.add(flag+"");
			
			li.add(TimeUtils.getCurDate());
			li.add(oms);

			list.add(li);

			Excel2003Writer
					.writeExcelAppend("E:\\vecodes\\aftersale.xls", list);
		} catch (Exception e) {
			LogUtils.error(log, e.toString());
			throw e;
		}
	}

	public Set<String> readExce() {
		File file = new File("E:\\vecodes\\aftersale.xlsx");
		File file1 = new File("E:\\vecodes\\aftersale.xls");

		Set<String> set = new HashSet<String>();
		FileInputStream in = null;
		try {
			in = new FileInputStream(file);

			IRowReader reader = gerIRowReader(set);

			ExcelReaderUtil.readExcel(reader, in);

			in = new FileInputStream(file1);

			reader = gerIRowReader(set);

			ExcelReaderUtil.readExcel(reader, in);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != in) {
				IOUtils.closeQuietly(in);
			}

		}

		return set;

	}

	public IRowReader gerIRowReader(final Set<String> set) {
		IRowReader reader = new IRowReader() {

			public void getRows(int sheetIndex, String sheetName, int curRow,
					List<String> rowlist) {
				// 总库存金额

				if (0 == curRow) {
					return;
				}

				if (rowlist.size() > 3) {
					String oms = rowlist.get(3);

					if (!CommonUtils.isEmpty(oms)) {
						set.add(oms);
					}
				}

				if (rowlist.size() > 4) {
					String ok = rowlist.get(4);
					if (!CommonUtils.isEmpty(ok)) {
						set.remove(ok);
					}
				}

			}
		};

		return reader;
	}

	@Override
	public String catchSupplierName() throws BusinessException {
		initCompanyInfomation();
		String name = "";

		return name;
	}


	public void initCompanyInfomation() {

		// http://b2bi.gome.com.cn/gmol/sellVatInvQry/detail.hlt?invid=2041525

	}

	public void open() {
		try {
			this.getWebDriver()
					.get("http://202.104.30.176/mcss/enterapp.do?method=begin&name=/mcss&welcome=/mcss/pages/index.jsp");

			WebElement iframe = this.getWebDriver().findElement("css", 
					"body > iframe");
			this.getWebDriver().switchToframe(iframe);

			this.getWebDriver().switchToframe("middern");

			WebElement iframe2 = this.getWebDriver().findElement(
					WebDriverService.tagName, "iframe");
			this.getWebDriver().switchToframe(iframe2);

			WebElement iframe3 = this.getWebDriver().findElement("css",
					"body > iframe");
			this.getWebDriver().switchToframe(iframe3);

			int count = 5 ;
			while(count > 0){
				count -- ;
				WaitUtil.waitTimeSeconds(1);
				boolean flag = this.getWebDriver().IsExist("id", "ext-gen4");
				if(flag){
					this.getWebDriver().click("id", "ext-gen4");
					break ;
				}
			}
			

		} catch (Exception e) {
			LogUtils.info(log, e.getMessage());
			throw e;
		}

	}

	public void add() {
		try {
			this.getWebDriver().switchToDefaultContent();

			WebElement iframe = this.getWebDriver().findElement("css",
					"body > iframe");

			this.getWebDriver().switchToframe(iframe);

			this.getWebDriver().switchToframe("middern");

			this.getWebDriver().switchToframe("page_1353077286424");
            
			int count = 5 ;
			while(count > 0){
				count -- ;
				WaitUtil.waitTimeSeconds(1);
				boolean flag = this.getWebDriver().IsExist("css",
						"#btnAdd > button > table > tbody > tr > td.u-form-btn-txt");
				if(flag){
					this.getWebDriver()
					.click("css",
							"#btnAdd > button > table > tbody > tr > td.u-form-btn-txt");
					break ;
				}
			}
			
		} catch (Exception e) {

 			LogUtils.info(log, e.getMessage());
			throw e;
		}
	}

	public String deal(String type) {
		String message = "";
		try {
			String bigError = "";
			this.getWebDriver().switchToDefaultContent();

			List<WebElement> iframes = this.getWebDriver().findElements(
					WebDriverService.tagName, "iframe");

			WebElement iframe3 = iframes.get(2);

			this.getWebDriver().switchToframe(iframe3);

			List<WebElement> divs = null;
			int count = 5 ;
			while(count > 0){
				count -- ;
				WaitUtil.waitTimeSeconds(1);
				boolean flag = this.getWebDriver().IsExist("css",
						"#baseTree > div > div.dijitTreeContainer > div > div.dijitTreeContainer .dijitTreeNode");
				if(flag){
					divs = this
							.getWebDriver()
							.findElements(
									"css",
									"#baseTree > div > div.dijitTreeContainer > div > div.dijitTreeContainer .dijitTreeNode");
					break ;
				}
			}
			
			
			if (!CommonUtils.isEmpty(divs)) {
				for (WebElement div : divs) {
					bigError = this
							.getWebDriver()
							.getText(div, "css",
									"div.treeRenderNode > table > tbody > tr > td:nth-child(4) > div");
					// TODO
					if (map.get(type).keySet().contains(bigError)) {
						WaitUtil.waitTimeSeconds(2);
						div.click();
						// this.getWebDriver().clearByJS(div);
						break;
					}

				}
			}

			WebElement td = this.getWebDriver().findElement("id",
					"unieap_grid_View_0");

			// #page-0 > div:nth-child(1) > table > tbody > tr > td:nth-child(2)
			// > div > div
			divs = this.getWebDriver().findElements(td, "css", "#page-0 > div");
			int select = 0;
			if (!CommonUtils.isEmpty(divs)) {
				for (int i = 0; i < divs.size(); i++) {

					message = this.getWebDriver().getText(divs.get(i),
							"css",
							"table > tbody > tr > td:nth-child(2) > div > div");

					if (map.get(type).get(bigError).contains(message)) {
						// radio.click();
						// this.getWebDriver().clearByJS(div);
						select = i;
						break;
					}

				}
			}

			td = this.getWebDriver().findElement("id", "unieap_grid_RowView_0");
			// #page-0 > div:nth-child(1) > table > tbody > tr >
			// td.u-grid-rowbar-choice >
			List<WebElement> radios = this.getWebDriver().findElements(td,
					"css", "input[type=\"radio\"]");

			WaitUtil.waitTimeSeconds(4);
			if (!CommonUtils.isEmpty(radios)) {
				radios.get(select).click();
			}
			
			
			this.getWebDriver().click(WebDriverService.xpath, "//*[@id=\"btnDo\"]/button/table/tbody/tr/td[2]");

		} catch (Exception e) {
			
            if(this.getWebDriver().IsExist("css", "#btnUndo > button > table > tbody > tr > td.u-form-btn-txt")){
            	this.getWebDriver().click("css", "#btnUndo > button > table > tbody > tr > td.u-form-btn-txt");
            }
            
            
			LogUtils.info(log, e.getMessage());
			//throw e;
		}

		return message;
	}

	public void deallast() {
		try {
			this.getWebDriver().switchToDefaultContent();

			List<WebElement> iframes = this.getWebDriver().findElements(
					WebDriverService.tagName, "iframe");
			WebElement iframe3 = iframes.get(2);
			// #unieap_dialog_Dialog_14 > div.u-dlg-mm > div.u-dlg-mmm >
			// div.u-dlg-mmf > div > iframe
			this.getWebDriver().switchToframe(iframe3);
			/*
			 * List<WebElement> divs = this .getWebDriver() .findElements("css",
			 * "#unieap_layout_BorderPane_0 > div.borderPane > div:nth-child(2) #page-0 div"
			 * );
			 */
			
			int count = 5 ;
			while(count > 0){
				count -- ;
				WaitUtil.waitTimeSeconds(1);
				boolean flag = this.getWebDriver().IsExist("css",
						"#ifileGrid > table.u-grid-master-views");
				if(flag){
					WebElement table = this.getWebDriver().findElement("css",
							"#ifileGrid > table.u-grid-master-views");

					WebElement div = this.getWebDriver().findElement(table, "css",
							"#page-0 > div:nth-child(1)");
					div.click();

					// #btnUndo > button > table > tbody > tr > td.u-form-btn-txt
					this.getWebDriver().click("css",
							"#btnDo > button > table > tbody > tr > td.u-form-btn-txt");
					break ;
				}
			}
			
			
			

		} catch (Exception e) {
			LogUtils.info(log, e.getMessage());
			//throw e;
		}

	}

	public void responsible(String deal) {
		try {
			this.getWebDriver().switchToDefaultContent();

			List<WebElement> iframes = this.getWebDriver().findElements(
					WebDriverService.tagName, "iframe");

			WebElement iframe3 = iframes.get(1);

			this.getWebDriver().switchToframe(iframe3);
			
			WaitUtil.waitTimeSeconds(5);

			try {
				this.getWebDriver()
						.click("css",
								"#SRESPONSIBLE_PARTY > div.u-form-field.u-form-readOnly > div.u-form-textbox-field > input");
				this.getWebDriver()
						.click("css",
								".u-combobox-list div.u-combobox-items-container > table > tbody > tr:nth-child(3) > td > span");

			} catch (Exception e) {
				this.getWebDriver()
						.click("css",
								"#SRESPONSIBLE_PARTY > div.u-form-field.u-form-readOnly > div.u-form-textbox-field > input");

				this.getWebDriver()
						.click("css",
								".u-combobox-list div.u-combobox-items-container > table > tbody > tr:nth-child(3) > td > span");

			}

			WebElement div = this.getWebDriver().findElement("id",
					"SDEC_DETAIL");
			WebElement input = this.getWebDriver().findElement(div,
					WebDriverService.tagName, "input");

			this.getWebDriver().sendKeys(input, deal + "坏");

			this.getWebDriver()
					.click("css",
							"#btnSave > button > table > tbody > tr > td.u-form-btn-txt");

		} catch (Exception e) {
			LogUtils.info(log, e.getMessage());
			throw e;
		}
		// 工厂制造或设计：出厂装配不良/漏装/错装，功能不良（非外观不良）等
		// #unieap_form_ComboBoxPopup_3 > div.u-combobox-items-container > table
		// > tbody > tr:nth-child(1) > td > span
	}

	public String dealcategory(String oms) {
		String message = "";
		try {

			this.getWebDriver().switchToDefaultContent();

			List<WebElement> iframes = this.getWebDriver().findElements(
					WebDriverService.tagName, "iframe");

			// http://202.104.30.176/mcss/forEdit.do
			this.getWebDriver().switchToframe(iframes.get(1));

			this.getWebDriver()
					.sendKeys(
							"css",
							"#SSERIAL_NUM1 > div.u-form-field > div.u-form-textbox-field > input",
							oms);

			this.getWebDriver()
					.sendKeys(
							"css",
							"#BATCH_NO  > div.u-form-field > div.u-form-textbox-field > input",
							"8");

			this.getWebDriver().switchToDefaultContent();

			iframes = this.getWebDriver().findElements(
					WebDriverService.tagName, "iframe");

			if (!CommonUtils.isEmpty(iframes)) {
				Iterator<WebElement> it = iframes.iterator();
				while (it.hasNext()) {
					WebElement ifame = it.next();
					if (ifame
							.getAttribute("src")
							.equals("http://202.104.30.176/mcss/mcss/pages/cs/sf/comm/product/newProduct.jsp")) {
						this.getWebDriver().switchToframe(ifame);

						WebElement td = this.getWebDriver().findElement("id",
								"unieap_grid_View_0");

						List<WebElement> divs = this.getWebDriver()
								.findElements(td, "css", "#page-0 > div");
						int select = 0;
						if (!CommonUtils.isEmpty(divs)) {
							for (int i = 0; i < divs.size(); i++) {

								message = this
										.getWebDriver()
										.getText(divs.get(i), "css",
												" table > tbody > tr > td:nth-child(5) > div > div");
								// TODO 产品大类
								if (set.contains(message)) {
									// radio.click();
									// this.getWebDriver().clearByJS(div);
									select = i;
									break;
								}

							}
						}

						td = this.getWebDriver().findElement("id",
								"unieap_grid_RowView_0");
						// #page-0 > div:nth-child(1) > table > tbody > tr >
						// td.u-grid-rowbar-choice >
						List<WebElement> radios = this.getWebDriver()
								.findElements(td, "css",
										"input[type=\"radio\"]");

						if (!CommonUtils.isEmpty(radios)) {
							radios.get(select).click();
						}

						WebElement save = this
								.getWebDriver()
								.findElement("css",
										"#btnAccept > button > table > tbody > tr > td.u-form-btn-txt");
						// this.getWebDriver().click(divs.get(0),
						// WebDriverService.tagName, "input");
						// this.getWebDriver().clickByJS(save);
						save.click();

					}
				}
			}

			this.getWebDriver().switchToDefaultContent();

			this.getWebDriver().switchToframe(iframes.get(1));

			this.getWebDriver()
					.sendKeys(
							"css",
							"#BATCH_NO  > div.u-form-field > div.u-form-textbox-field > input",
							"8");

			if(CommonUtils.isEmpty(message)){
				message =  this.getWebDriver().getTextByJS("css", "#SPRODUCT_TYPE > div.u-form-field.u-form-readOnly.u-form-disabled > div.u-form-textbox-field > input");
			}
			
			int count = 5 ;
			while(count > 0){
				count -- ;
				WaitUtil.waitTimeSeconds(1);
				boolean flag = this.getWebDriver().IsExist("css",
						"#SFAULT_ID_CODE > div.u-form-field.u-form-readOnly.u-form-textbox-error > div:nth-child(3) > input");
				if(flag){
					this.getWebDriver()
					.click("css",
							"#SFAULT_ID_CODE > div.u-form-field.u-form-readOnly.u-form-textbox-error > div:nth-child(3) > input");
					break ;
				}
			}
		} catch (Exception e) {
			LogUtils.info(log, e.getMessage());
			throw e;
		}

		return message;
	}

	public void retuns() {
		try {
			this.getWebDriver().switchToDefaultContent();
			WaitUtil.waitTimeSeconds(4);
			// 测试可以
			try {
				this.getWebDriver().click("css",
						".u-dlg  .u-dlg-mmb .u-form-btn-outer .u-form-btn");
			} catch (Exception e) {

			}

			List<WebElement> iframes = this.getWebDriver().findElements(
					WebDriverService.tagName, "iframe");

			// http://202.104.30.176/mcss/forEdit.do
			this.getWebDriver().switchToframe(iframes.get(1));

			WaitUtil.waitTimeSeconds(1);
			this.getWebDriver()
					.click("css",
							"#btnCanceled > button > table > tbody > tr > td.u-form-btn-txt");
		} catch (Exception e) {
			LogUtils.info(log, e.getMessage());
			throw e;
		}

	}

	public boolean doit(String oms) {
		try {
			add();
			
			String type = dealcategory(oms);

			String deal = deal(type);

			deallast();

			responsible(deal);

			retuns();

		} catch (Exception e) {
			LogUtils.info(log, e.getMessage());
			return false;
		}

		return true;
	}

	@Override
	public boolean getUnpayAccountData() throws BusinessException {
		return true;

	}

	@Override
	public boolean getInstoreOrderData() throws BusinessException {

		return true;
	}

	@Override
	public boolean getOutstoreOrderData() throws BusinessException {
		// 送货记录
		// 对账单
		return true;
	}

	@Override
	public boolean getPayAccountData() throws BusinessException {
		return true;
	}

	@Override
	public BankCardCheck catchSupplierAccount() throws BusinessException {
		// TODO Auto-generated method stub
		return null;
	}

}
